﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Routing;
using TiTi.tea.Api.Attributes;
using TiTi.tea.Api.Models;
using TiTi.tea.BLL;
using TiTi.tea.Comm;

namespace TiTi.tea.Api.Controllers
{
    [RoutePrefix("api/customer")]
    public class CustomerController : ApiController
    {
        /// <summary>
        /// 根据价格获取可用优惠卷
        /// </summary>
        /// <param name="amount"></param>
        /// <returns></returns>
        [Route("getCoupon")]
        [HttpGet]
        [MyAuthorize]
        public Result GetCoupons()
        {
            IHttpRouteData routeData = Request.GetRouteData();
            IDictionary<string, object> dict = routeData.Values;
            var auth = dict["auth"] as AuthInfo;
            var userId = auth.UserId;

            UserCouponBLL userCoupon = new UserCouponBLL();

            var data = userCoupon.Get(userId);
            return Result.Success(data);
        }

        /// <summary>
        /// 订单添加
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        [Route("addOrder")]
        [HttpPost]
        [MyAuthorize]
        public Result AddOrder(OrderVM order)
        {
            IHttpRouteData routeData = Request.GetRouteData();
            IDictionary<string, object> dict = routeData.Values;
            var auth = dict["auth"] as AuthInfo;
            var userId = auth.UserId;

            OrderInfoBLL orderBll = new OrderInfoBLL();
            UserCouponBLL userCouponBll = new UserCouponBLL();
            IntegralsInfoBLL integralsBll = new IntegralsInfoBLL();

            // 添加积分
            integralsBll.Add(userId,order.Info.Amount);

            order.Info.UserId = userId;
            var info = orderBll.Add(order.Info, order.Details);
            if (order.CouponId != null) userCouponBll.Update(order.CouponId??0, 2);

            if (info != null)
            {
                return Result.Success(info);
            }
            else
            {
                return Result.Error("添加失败");
            }
        }

    }
}